﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Mokey.Common.Forms
{
    public class FormFader
    {
        private Form _formToFade;
        private const int FRAME_RATE = 20;
        private double _fadeInOpacityDelta;
        private double _fadeOutOpacityDelta;
        private double _currentFadeDelta;
        Timer _fadeTimer;

        public FormFader(Form formToFade, int fadeTime)
        {
            _formToFade = formToFade;
            _fadeTimer = new Timer();
            _fadeTimer.Interval = 1000 / FRAME_RATE;
            _fadeInOpacityDelta = 1.0 / (fadeTime * FRAME_RATE);
            _fadeOutOpacityDelta = -1.0 * _fadeInOpacityDelta;
            _fadeTimer.Tick += new EventHandler(_fadeTimer_Tick);
        }

        private void _fadeTimer_Tick(object sender, EventArgs e)
        {
            _formToFade.Opacity = Math.Min(Math.Max(_formToFade.Opacity + _currentFadeDelta, 0.0), 1.0);
            if (_formToFade.Opacity == 1 || _formToFade.Opacity == 0)
            {
                _fadeTimer.Stop();
                _fadeTimer.Enabled = false;
                if (FadingFinished != null)
                {
                    FadingFinished(this, new EventArgs());
                }
            }
        }

        /// <summary>
        /// Fade in/out time in seconds
        /// </summary>
        public int FadeTime { get; set; }

        public void FadeIn()
        {
            _formToFade.Opacity = 0;
            _currentFadeDelta = _fadeInOpacityDelta;
            _fadeTimer.Enabled = true;
            _fadeTimer.Start();
        }

        public void FadeOut()
        {
            _formToFade.Opacity = 1;
            _currentFadeDelta = _fadeOutOpacityDelta;
            _fadeTimer.Enabled = true;
            _fadeTimer.Start();
        }

        public void CancelFade()
        {
            _fadeTimer.Stop();
            _fadeTimer.Enabled = false;
        }

        public event EventHandler FadingFinished;
    }
}
